<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Wechatpay extends Auth_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model("user_model","user");
        $this->load->model("point_model","point");
    }

    public function test()
    {
        $json_content = urldecode(file_get_contents('php://input')) ? urldecode(file_get_contents('php://input')) : 'clientOs=1';
        file_put_contents("tixian.txt", date("Y-m-d H:i:s", time())."--".$json_content."\r\n",FILE_APPEND);
        // $params['amount'] = $this->queryData["amount"];
        $params['amount'] = 1;
        $validate = new Validate([
            'amount' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $userInfo = $this->userDetail;
        //查询当前用户的总金额
        if($params['amount'] > $userInfo['money'])
        {
            $this->errorCode = 90012;
            $this->createApi();
            exit;
        }
        try {
            $thirdInfo = $this->user->getThirdPartInfo($userInfo['AccountID']);
            $openid = $thirdInfo['thirdPartyId']; 
            if($openid)
            {
                $payResult = $this->payToUser($openid, "提现成功", $params['amount']);
                file_put_contents("tixian.txt", date("Y-m-d H:i:s", time())."--result:".$payResult."\r\n",FILE_APPEND);

                if($payResult['return_code'] != "SUCCESS")
                {
                    throw new Exception($payResult['return_msg']);
                    
                }
                //添加提取现金记录
                $payData = [
                            'money'=>$params['amount']*-1,
                            'AccountID'=>$userInfo['AccountID'],
                            'type'=>13,
                            'createtime'=>date("Y-m-d",time()),
                            'correcttime'=>time()
                        ];      
                $res = $this->point->addAnswerMoney($payData);
            }    
            $this->createApi();exit;  
        } catch (Exception $e) {
            $this->errorCode = 90013;
            $this->errorMessage = $e->getMessage;
            $this->createApi();exit;
        }
        
    }
    /**
     *  array转xml
     */
    
    //企业向个人付款
    public function payToUser($openid='',$desc='提现成功',$amount='1')
    {
        //微信付款到个人的接口
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

        $params["mch_appid"]        = '';   //公众账号appid
        $params["mchid"]            = '';   //商户号 微信支付平台账号
        $params["nonce_str"]        = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890'.mt_rand(100,999);   //随机字符串
        $params["partner_trade_no"] = mt_rand(10000000,99999999);           //商户订单号
        $params["amount"]           = $amount;          //金额
        $params["desc"]             = $desc;            //企业付款描述
        $params["openid"]           = $openid;          //用户openid
        $params["check_name"]       = 'NO_CHECK';       //不检验用户姓名
        $params['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];   //获取IP

                //生成签名(签名算法后面详细介绍)
        $str = 'amount='.$params["amount"].'&check_name='.$params["check_name"].'&desc='.$params["desc"].'&mch_appid='.$params["mch_appid"].'&mchid='.$params["mchid"].'&nonce_str='.$params["nonce_str"].'&openid='.$params["openid"].'&partner_trade_no='.$params["partner_trade_no"].'&spbill_create_ip='.$params['spbill_create_ip'].'&key=F5YguNW77Ao4N5yu5wZ8Lb00NKOg1Y04';
        //md5加密 转换成大写
        $sign = strtoupper(md5($str));

        $params["sign"] = $sign;//签名

        $xml = $this->arrayToXml($params);

        return $this->curlPostSsl($url, $xml, 30);

    }
    
    public function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) 
        {
            if (is_numeric($val)) 
            {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        $xml .= "</xml>";
        return $xml;
        }
    }
    //使用证书，以post方式提交xml到对应的接口url

    /**
     *   作用：使用证书，以post方式提交xml到对应的接口url
     */
    public function curlPostSsl($url, $vars, $second=30)
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种
        /******* 此处必须为文件服务器根目录绝对路径 不可使用变量代替*********/
        curl_setopt($ch,CURLOPT_SSLCERT,"/home/lizi/addons/grow/template/mobile/cash/apiclient_cert.pem");
        curl_setopt($ch,CURLOPT_SSLKEY,"/home/lizi/addons/grow/template/mobile/cash/apiclient_key.pem");


        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);

        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            return "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

   
}
